package demo;

public class ThreadSafe {

        private static final int N =100_0000;
        static int a=0;//两个线程的共享数据a
        static Object lock=new Object();//创建一个对象锁

        static class SubThread1 extends Thread{
                @Override
                public void run() {
                        synchronized(lock){
                                //在访问共享数据a时要对a加锁并且加同一把锁才能保证原子性
                                for(int i=0;i<N;i++){
                                        a++;
                                }
                        }
                }
        }

        static class SubThread2 extends Thread{
                @Override
                public void run() {
                        synchronized(lock){
                                //加锁与解锁之间称为临界区
                                for(int i=0;i<N;i++){
                                        a--;
                                }
                        }
                }
        }

        public static void main(String[] args) throws Exception {
                 Thread t1=new SubThread1();
                 t1.start();
                 Thread t2=new SubThread2();
                 t2.start();

                 t1.join();
                 t2.join();

                 System.out.println(a);

                 //用锁保障了对a这个共享数据的操作时的原子性
                 //线程安全，得到预期结果0
        }
        }
